package com.song.tools.songtest.config;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.collection.CollUtil;
import com.song.tools.songtest.beans.bo.SysRoleBo;
import com.song.tools.songtest.beans.bo.SysRoleUserBo;
import com.song.tools.songtest.beans.query.SysRoleUserQuery;
import com.song.tools.songtest.manager.SysRoleManager;
import com.song.tools.songtest.manager.SysRoleUserManager;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义权限加载接口实现类<br>
 * 参考：<a href="https://sa-token.cc/doc.html#/use/jur-auth">https://sa-token.cc/doc.html#/use/jur-auth</a>
 *
 * @author backend-manage
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private SysRoleManager sysRoleManager;

    @Resource
    private SysRoleUserManager sysRoleUserManager;

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        return new ArrayList<>();
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        // 查用户角色关联关系
        SysRoleUserQuery sysRoleUserQuery = new SysRoleUserQuery();
        sysRoleUserQuery.setUserId(Long.valueOf(loginId.toString()));
        List<SysRoleUserBo> sysRoleUserBos = sysRoleUserManager.list(sysRoleUserQuery);
        if (CollUtil.isEmpty(sysRoleUserBos)) {
            return new ArrayList<>();
        }

        // 通过角色ID列表查角色信息
        List<Long> roleIds = sysRoleUserBos.stream().map(SysRoleUserBo::getRoleId).toList();
        List<SysRoleBo> sysRoleBos = sysRoleManager.listByPrimaryKeys(roleIds);
        if (CollUtil.isEmpty(sysRoleBos)) {
            return new ArrayList<>();
        }

        // 返回角色编码
        return sysRoleBos.stream().map(SysRoleBo::getCode).collect(Collectors.toList());
    }
}
